<script>
import { getAllShops, saveShop, getShop } from './api/shop.js'
import { getAllProvinces, getCitys, getCountrys } from './api/china.js'
import { ElMessage } from 'element-plus'
export default {
    data() {
        return {
            layout: 'center',
            shops: [],
            isModalVisible: false,
            provinceValue: "请选择省",
            provinces: [],
            citys: [],
            countrys: [],
            disabled: false,
            currentPage: 1,
            pageSize: 5,
            background: false,
            info: {
                name: '', // 绑定总店名的数据
                code: ''  // 绑定总店编码的数据
            },
            shopForm: {
                code: '',
                name: '',
                province: '请选择省',
                city: '请选择市',
                country: '请选择区',
                address: '',
                contact: '',
                phone: ''
            },
            rules: {
                code: [
                    { required: true, message: '请输入总店编号', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入总店名', trigger: 'blur' }
                ],
                province: [
                    { required: true, message: '请选择省份', trigger: 'change' }
                ],
                city: [
                    { required: true, message: '请选择城市', trigger: 'change' }
                ],
                address: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ],
                contact: [
                    { required: true, message: '请输入联系人', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '联系电话格式不正确', trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.shops.slice(start, end);
        }
    },
    async mounted() {
        try {
            const response = await getAllShops();
            this.shops = response.data; // 假设返回的数据在response.data中
        } catch (error) {
            console.error('Failed to fetch shops:', error);
        }
    },
    methods: {
        async showModal() {
            this.isModalVisible = true; // 显示模态框
            const response = await getAllProvinces();
            let regionArray = [];
            for (let region of response.data) {
                regionArray.push({
                    value: region,
                    label: region
                });
            }
            this.provinces = regionArray;
        },
        async getCitys() {
            try {
                const response = await getCitys(this.shopForm.province);
                let regionArray = [];
                for (let region of response.data) {
                    regionArray.push({
                        value: region,
                        label: region
                    });
                }
                this.citys = regionArray;
            } catch (error) {
                console.error('Failed to fetch cities:', error);
            }
        },
        async getCountrys() {
            try {
                const response = await getCountrys(this.shopForm.city);
                console.log(response)
                let regionArray = [];
                for (let region of response.data) {
                    regionArray.push({
                        value: region,
                        label: region
                    });
                }
                this.countrys = regionArray;
            } catch (error) {
                console.error('Failed to fetch cities:', error);
            }
        },
        hideModal() {
            this.isModalVisible = false; // 隐藏模态框
        },
        async saveShop() {
            this.$refs.shopForm.validate(async (valid) => {
                if (valid) {
                    this.isModalVisible = false;
                    try {
                        const response = await saveShop(this.shopForm);
                        console.log(response)
                        if (response.code === 1) {
                            ElMessage({
                                message: response.message,
                                type: 'success'
                            });
                            this.resetForm()
                        } else {
                            ElMessage({
                                message: response.message,
                                type: 'error'
                            });
                        }
                    } catch (error) {
                        ElMessage({
                            message: '保存店铺时发生错误，请检查网络或联系管理员',
                            type: 'error'
                        });
                        console.error('保存店铺时发生错误:', error);
                    }
                } else {
                    ElMessage({
                        message: '请输入信息',
                        type: 'error'
                    });
                }
            });
        },
        resetForm() {
            this.shopForm.code = '';
            this.shopForm.name = '';
            this.shopForm.province = '请选择省';
            this.shopForm.city = '请选择市';
            this.shopForm.country = '请选择区';
            this.shopForm.address = '';
            this.shopForm.contact = '';
            this.shopForm.phone = '';
        },
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.currentPage = 1; // Reset to first page
        },
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
        },
        async onSubmit() {
            if (this.info.name === '' && this.info.code === '') {
                ElMessage({
                    message: '请输入总店姓名或者编号',
                    type: 'error'
                });
                return
            }
            const response = await getShop(this.info)
            this.shops = response.data
        },
        async onClear() {
            this.info = {}
            try {
                const response = await getAllShops();
                this.shops = response.data; // 假设返回的数据在response.data中
            } catch (error) {
                console.error('Failed to fetch shops:', error);
            }
        }
    }
}
</script>

<template>
    <el-card style="max-width: 90%; margin: 10% auto;">
        <el-form :inline="true" :model="info">
            <el-form-item label="总店名">
                <el-input placeholder="请输入总店名" v-model="info.name" clearable />
            </el-form-item>

            <el-form-item label="总店编码">
                <el-input placeholder="请输入总店编码" v-model="info.code" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onClear">清空</el-button>
            </el-form-item>
        </el-form>
        <el-button type="primary" @click="showModal">添加总店</el-button>
        <el-table :data="paginatedData" style="width: 100%" :align="layout">
            <el-table-column type="index" label="编号" width="180" :align="layout" />
            <el-table-column prop="code" label="总店编号" width="180" :align="layout" />
            <el-table-column prop="name" label="总店名" :align="layout" />
            <el-table-column prop="contact" label="联系人" :align="layout" />
            <el-table-column prop="phone" label="联系电话" :align="layout" />
            <el-table-column label="操作" :align="layout">
                <el-button type="primary">查看分店</el-button>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            :disabled="disabled" :background="background" layout="prev, pager, next, jumper, total, sizes"
            :total="shops.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 模态框结构 -->
    <el-dialog v-model="isModalVisible" title="添加总店" :before-close="hideModal">
        <!-- 模态框内容 -->
        <el-form :model="shopForm" :rules="rules" ref="shopForm">
            <!-- 表单内容 -->
            <el-form-item label="总店编号" prop="code">
                <el-input v-model="shopForm.code" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="总店名" prop="name" style="margin-left: 14px;">
                <el-input v-model="shopForm.name" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="所在地区">
                <el-row>
                    <el-col :span="8">
                        <!-- 省份选择器 -->
                        <el-select v-model="shopForm.province" style="width: 200px; margin-left: 10px;"
                            @change="getCitys" prop="province">
                            <el-option v-for="item in provinces" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <!-- 城市选择器 -->
                        <el-select v-model="shopForm.city" style="width: 200px; margin-left: 10px;"
                            @change="getCountrys" prop="city">
                            <el-option v-for="item in citys" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <!-- 区县选择器 -->
                        <el-select v-model="shopForm.country" style="width: 200px; margin-left: 10px;" prop="address">
                            <el-option v-for="item in countrys" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input v-model="shopForm.address" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="contact" style="margin-left: 14px;">
                <el-input v-model="shopForm.contact" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="shopForm.phone" placeholder="请输入"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="hideModal">取消</el-button>
            <el-button type="primary" @click="saveShop">确定</el-button>
        </span>
    </el-dialog>
</template>